<?php

namespace app\utils\aliyun;

use app\utils\http\HttpClient;
use GuzzleHttp\Exception\GuzzleException;
use think\Exception;

class OcrIdcard
{
//    protected string $host = "https://dfidcard.market.alicloudapi.com";
    protected string $host = "http://dfidcard.market.alicloudapi.com";
    protected string $path = "/ocr/idcard";
    protected string $method = "POST";
    protected string $appcode = "a68b0ef8c8be43aeb5c73e906006e510";
    protected string $url;
    protected array $headers = array();
    
    public function __construct()
    {
        $this->url = $this->host . $this->path;
        $this->headers = [
            "Authorization" => 'APPCODE ' . $this->appcode,
            //根据API的要求，定义相对应的Content-Type
            "Content-Type" => "application/x-www-form-urlencoded; charset=UTF-8"
        ];
    }
    
    public static function instance(): OcrIdcard
    {
        return new static();
    }
    
    /**
     * @param $id_number
     * @param $name
     * @return object|string
     * @throws GuzzleException
     * @throws Exception
     */
    public function verify($image_url)
    {
        // $bodys = "id_number=445122********33&name=%E9%BB%84%E5%A4%A7%E5%A4%A7";
        $response = HttpClient::createInstance()->postRequest($this->url, [
            'image_url' => $image_url,
        ], $this->headers);
        Logs($response, 'OcrIdcard');
        if (empty($response)) {
            $response = new \ArrayObject();
            $response->noServe = true;
            $response->verify = false;
            return $response;
        }
        $response->noServe = false;
        $response->verify = true;
        
        if (!isset($response->status) || $response->status != 'OK') {
            $response->verify = false;
        }
        return $response;
    }
    
    public function verifyIdCardFrontImg($image_url)
    {
        $verify = $this->verify($image_url);
        Logs($verify, 'verifyIdCardFrontImg');
        return $verify;
    }
    
    public function verifyIdCardBackImg($image_url)
    {
        $verify = $this->verify($image_url);
        Logs($verify, 'verifyIdCardBackImg');
        return $verify;
    }

}